package tx_chat

import (
	"encoding/json"
	"longmen/server/internal/rpc/tencentim/subscribe"
	"longmen/server/internal/services/consumers/publisher"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/lib/rabbitmq"
	"sync"

	"go.uber.org/zap"
)

type TxChat struct {
	logger *zap.SugaredLogger
	tx     *subscribe.TxChat
}

var instance *TxChat
var once sync.Once
var funcMaps = map[_const.BroadCastType]rabbitmq.Process{}

func NewTxChat(log *zap.SugaredLogger) *TxChat {
	once.Do(func() {
		instance = &TxChat{
			logger: log,
			tx:     subscribe.NewTxChat(log),
		}
		funcMaps = map[_const.BroadCastType]rabbitmq.Process{
			publisher.GiftHeat:        instance.tx.GiftHeatCalculator,
			publisher.ClearChat:       instance.tx.ClearChat,
			publisher.Login:           instance.tx.LoginBroadcast,
			publisher.AnonymousLogin:  instance.tx.AnoLoginBroadcast,
			publisher.SubscribeAnchor: instance.tx.SubscribeAnchor,
			publisher.ChangeProps:     instance.tx.UserPropsUpdate,
			publisher.AdminLog:        instance.tx.SubAdminLogMessage,
			publisher.HistoryToEs:     instance.tx.ChatHistoryToEs,
			publisher.AllMemberPush:   instance.tx.AllMemberPush,
			publisher.AutoChat:        instance.tx.AutoChatPush,
		}
	})
	return instance
}

func (t *TxChat) Process(data []byte) bool {
	resp := publisher.BroadCastMessage{}
	err := json.Unmarshal(data, &resp)
	if err != nil {
		t.logger.Errorf("process msg error: %v", err)
		return false
	}
	process, ok := funcMaps[resp.TypeName]
	if !ok {
		t.logger.Errorf("process not exists error: %s", resp.TypeName)
		return false
	}

	return process(resp.Msg)
}
